package com.platform.generate.core.util;

import cn.hutool.db.DbUtil;
import cn.hutool.db.Entity;
import cn.hutool.db.handler.EntityListHandler;
import cn.hutool.db.sql.SqlExecutor;
import cn.hutool.log.Log;
import com.google.common.collect.Lists;
import com.platform.generate.modular.result.InforMationColumnsResult;
import com.platform.core.exception.ServiceException;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;

/**
 * 获取表中字段工具类
 *
 */
public class ColumnsUtil {

    private static final Log log = Log.get();

    private static final String DATA_SOURCE_SQL = " select column_name,data_type,column_comment,column_key " +
            "from information_schema.columns where table_schema = ? and table_name = ?";

    private static final String COLUMN_NAME = "column_name";

    private static final String DATA_TYPE = "data_type";

    private static final String COLUMN_KEY = "column_key";

    private static final String COLUMN_COMMENT = "column_comment";


    public static List<InforMationColumnsResult> columns(String url, String account, String password, String tableName) {

        Connection conn = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            // 获取数据库连接配置
            String dataSourceUrlCurrent = url;
            String dataSourceUsernameCurrent = account;
            String dataSourcePasswordCurrent = password;

            String dbName = Util.getDataBasename(url,"mysql");
            conn = DriverManager.getConnection(dataSourceUrlCurrent, dataSourceUsernameCurrent, dataSourcePasswordCurrent);

            List<Entity> dataSourceEntity = SqlExecutor.query(conn, DATA_SOURCE_SQL, new EntityListHandler(),dbName,tableName);
            List<InforMationColumnsResult> results = Lists.newArrayList();
            for(Entity entity : dataSourceEntity){
                InforMationColumnsResult inforMationColumnsResult = new InforMationColumnsResult();
                inforMationColumnsResult.setColumnComment(entity.get(COLUMN_COMMENT)+"");
                inforMationColumnsResult.setColumnKey(entity.get(COLUMN_KEY)+"");
                inforMationColumnsResult.setColumnName(entity.get(COLUMN_NAME)+"");
                inforMationColumnsResult.setDataType(entity.get(DATA_TYPE)+"");
                results.add(inforMationColumnsResult);
            }
            return results;

        } catch (SQLException | ClassNotFoundException e) {
            log.error(">>> 读取数据库constants配置信息出错：");
            e.printStackTrace();
            throw new ServiceException(1,"数据库连接失败，请检查用户名密码是否正确。");
        } finally {
            DbUtil.close(conn);
        }

    }
}
